﻿using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using DirectShowLib;

namespace JAP.NET
{
    public partial class fmFilters : Form
    {
        public IGraphBuilder filterBuilder { get; set; }
        private IEnumFilters filters = null;
        public fmFilters()
        {
            InitializeComponent();
        }

        private void fmFilters_Load(object sender, EventArgs e)
        {
            BuildFilterTree();
        }

        private void BuildFilterTree ()
        {
            lbFilters.Items.Clear();
            if (filterBuilder == null)
            {
                lbFilters.Items.Add("<Nothing>");
                return;
            }
            var hr = filterBuilder.EnumFilters(out filters);
            DsError.ThrowExceptionForHR(hr);
            if (hr != 0) return;
            var currFilters = new IBaseFilter[1];
            while (filters.Next(currFilters.Length,currFilters,IntPtr.Zero) == 0)
            {
                FilterInfo filterInfo;
                hr = currFilters[0].QueryFilterInfo(out filterInfo);
                if (hr != 0) return;
                if (filterInfo.pGraph == null) continue;
                lbFilters.Items.Add(filterInfo.achName);
            }
        }

        private void btClose_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void ShowFilterProperties()
        {
           if (filterBuilder == null) return;
            var filt = new IBaseFilter[1];
            var hr = filterBuilder.FindFilterByName(lbFilters.SelectedItem.ToString(),out filt[0]);
            DsError.ThrowExceptionForHR(hr);
            if ((filt[0] as ISpecifyPropertyPages) == null) return;
            FilterInfo filtInfo;
            hr = filt[0].QueryFilterInfo(out filtInfo);
            DsError.ThrowExceptionForHR(hr);
            DsCAUUID caGuid;
            object[] objs;
            hr = ((ISpecifyPropertyPages) filt[0]).GetPages(out caGuid);
            DsError.ThrowExceptionForHR(hr);
            try
            {
                objs = new object[1];
                objs[0] = filt[0];

                 NativeMethods.OleCreatePropertyFrame(
                    this.Handle, 0, 0,
                    filtInfo.achName,
                    objs.Length, objs,
                    caGuid.cElems, caGuid.pElems,
                    0, 0,
                    IntPtr.Zero
                    );
            }
            finally
            {
                Marshal.FreeCoTaskMem(caGuid.pElems);
            }

            
        }

        private void btProperies_Click(object sender, EventArgs e)
        {
            ShowFilterProperties();
        }

        private void lbFilters_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            ShowFilterProperties();
        }
    }
}
